package com.coder.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.coder.model.User;

public class UserDao {
	
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		Session session = null;
		try {
			session = sessionFactory.getCurrentSession();
		} catch (Exception e) {
			session = sessionFactory.openSession();
		}
    	return session;
	}

	public User getUserByPara(String para,String value){
		Session session = getSession();
		Query query = null;
		try{
			query = session.createQuery("from User where "+para+"=?")
					.setString(0, value);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(query.list().size() == 0){
			return null;
		}else{
			return (User)query.list().get(0);
		}
	}
	
	public User saveOrUpdate(User user){
		Session session = getSession();
		try{
			session.saveOrUpdate(user);
		}catch(Exception e){
			e.printStackTrace();
		}
		return user;
	}

	//用邮箱或者用户名登录
	public boolean checkUserExist(User user) {
		Session session = getSession();
		//session.beginTransaction();
		Query query = null;
		try{
			query = session.createQuery("from User where (username=? and password=?) or (email=? and password=?)")
					.setString(0, user.getUsername().trim())
					.setString(1, user.getPassword().trim())
					.setString(2, user.getUsername().trim())
					.setString(3, user.getPassword().trim());
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if(query.list().size()==0){
			return false;
		}
		
		return true;
	}
	
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

 
}
